package token;
/**
 * A node in a binary tree.. kinda confusing, I know.
 * When adding a Tree node, please specify if it should retain
 * the children nodes of the node it is replacing. This is done
 * with a true (for keeping) and false (for releasing) inside the
 * addLeft() and addRight() methods.
 * @author Justin
 *
 */
public class BTree {
	String type;
	BTree left, right;
	public BTree(String s){
		type = s;
		left = null;
		right = null;
	}
	
	public BTree Traverse(String s){
		if (type == s){
			return this;
		}
		if (left != null){
			left.Traverse(s);
		}
		if (right != null){
			right.Traverse(s);
		}
		return null;
	}
	
	/**
	 * FOR INTERNAL USE ONLY
	 * sets the left node as the node given
	 * @param tree
	 */
	public void setLeft(BTree tree){
		left = tree;
	}
	/**
	 * FOR INTERNAL USE ONLY
	 * sets the right node as the node given
	 * @param tree
	 */
	public void setRight(BTree tree){
		right = tree;
	}
	/**
	 * replaces the left node with a node of String s
	 * if retain is true, retains the node's children and attaches them to the new node
	 * else replaces the node and releases the nodes
	 * @param s
	 * @param retain
	 * @return
	 */
	public BTree addLeft(String s, boolean retain){
		if (retain && left != null){
			BTree tLeft = left.getLeft();
			BTree tRight = left.getRight();
			left = new BTree(s);
			left.setLeft(tLeft);
			left.setRight(tRight);
		}
		else{
			left = new BTree(s);
		}
		return left;
	}
	/**
	 * replaces the right node with a node of String s
	 * if retain is true, retains the node's children and attaches them to the new node
	 * else replaces the node and releases the nodes
	 * @param s
	 * @param retain
	 * @return
	 */
	public BTree addRight(String s, boolean retain){
		if (retain && right != null){
			BTree tLeft = right.getLeft();
			BTree tRight = right.getRight();
			right = new BTree(s);
			right.setLeft(tLeft);
			right.setRight(tRight);
		}
		else{
			right = new BTree(s);
		}
		return right;
	}
	/**
	 * returns the right node
	 * @return
	 */
	public BTree getRight(){
		return right;
	}
	/**
	 * returns the left node
	 * @return
	 */
	public BTree getLeft(){
		return left;
	}
	
	public String getType() {
		return type;
	}
}
